package com.csdj.springboottest.controller;

import com.csdj.springboottest.common.CommonConstant;
import com.csdj.springboottest.entity.User;
import com.csdj.springboottest.service.UserService;
import com.csdj.springboottest.util.RandomUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public String login(@RequestParam(value = "username",required = true) String username,
                        @RequestParam(value = "password",required = true)String password,
                        HttpServletResponse response, ModelMap map){
        String token = RandomUtil.getToken();
        User user = userService.login(username, password, token);
        if(user == null) {
            map.put("msg", "密码和用户名不匹配");
            return "login";
        }
        Cookie cookie = new Cookie(CommonConstant.COOKIE_TOKEN, token);
        Cookie idCookie = new Cookie(CommonConstant.COOKIE_UID,String.valueOf(user.getId()));
        response.addCookie(cookie);
        response.addCookie(idCookie);
        map.put("user",user);
        return "index";
    }
}
